package cashpointer.mobile;

import android.app.TabActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import cashpointer.mobile.dao.DaoModel.Countries;
import cashpointer.mobile.dao.DaoModel.Regions;
import cashpointer.mobile.support.Functions;
import cashpointer.mobile.support.NotificationSupportManager;
import cashpointer.mobile.support.PreferencesManager;

public class ConfigActivity extends TabActivity {
	
	/**
	 * Opcje menu.
	 */
	private static final int MENU_QUIT = Menu.FIRST;
	
	//private static String LOG_TAG = "ConfigActivity";
	
	/**
     * The columns we are interested in from the database
     */	
	private static final String[] REGION_AND_COUNTRY_PROJECTION = new String[] {
    	Regions._ID, // 0
    	Regions.NAME, // 1
    };
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(android.R.style.Theme_Light);
        setContentView(R.layout.config);
        
        TabHost mTabHost = getTabHost();
        
        // Pierwsza zakladka
        CharSequence configTab1Title = getString(R.string.config_tab_1_title);
        mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator(configTab1Title).setContent(R.id.configTab1));
        
        // Druga zakladka
        CharSequence configTab2Title = getString(R.string.config_tab_2_title);
        mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator(configTab2Title).setContent(R.id.configTab2));
        
        // Ustawienie zakladki na pozycji pierwszej
        mTabHost.setCurrentTab(0);
        
        // TAB 1

        // Ustawiam zawartosc pola "Aktualna wersja"
        TextView currentVersionTextView = (TextView)findViewById(R.id.configCurrentVersionTextView);
        String currentVersion = PreferencesManager.getString(getApplicationContext(), PreferencesManager.CURRENT_VERSION, getString(R.string.config_default_version));
        currentVersionTextView.setText("Aktualna wersja: " + currentVersion);

        // Ustawiam zawartosc pola "Server Address"
        String serverAddress = PreferencesManager.getString(getApplicationContext(), PreferencesManager.SERVER_ADDRESS, getString(R.string.config_default_server)); 
        EditText serverAddressEditText = (EditText)findViewById(R.id.configServerAddressEditText);
        serverAddressEditText.setText(serverAddress);
        
        // Ustawiam zawartosc pola "Automatic upload"
        CheckBox automaticUploadCheckBox = (CheckBox)findViewById(R.id.configAutomaticUploadCheckBox);
        boolean automaticUpload = PreferencesManager.getBoolean(getApplicationContext(), PreferencesManager.IS_AUTOUPDATE_ON, false);
        automaticUploadCheckBox.setChecked(automaticUpload);

        // Ustawiam zawartosc pola "Google key maps"
        String googleKeyMaps = PreferencesManager.getString(getApplicationContext(), PreferencesManager.GOOGLE_KEY_MAPS, getString(R.string.config_default_google_key)); 
        EditText googleKeyMapsEditText = (EditText)findViewById(R.id.configGoogleKeyMapsEditText);
        googleKeyMapsEditText.setText(googleKeyMaps);
        
        // Pobieram przycisk "Aktualizuj baze teraz"
        Button saveButton = (Button)findViewById(R.id.configSaveButton);
        saveButton.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	ConfigActivity.this.save();
	        }
        });
        
        // TAB 2
        
        // Tworze adapter, ktory pobierze dane dla obiektu spinner
		Cursor regionChooseCursor = managedQuery(Regions.CONTENT_URI, REGION_AND_COUNTRY_PROJECTION, null, null, Regions.DEFAULT_SORT_ORDER);			
		SimpleCursorAdapter regionChooseAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, regionChooseCursor, new String[] {Regions.NAME}, new int[] {android.R.id.text1});
		regionChooseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
        // Pobieram spinner "Wybierz wojewodztwo" i ustawiam jego wartosc
        Spinner regionChooseSpinner = (Spinner) findViewById(R.id.configRegionChooseSpinner);
        regionChooseSpinner.setAdapter(regionChooseAdapter);
        
        // Pobieram identyfikator zapamietanego wojewodztwa
        long regionChooseId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.REGION_CHOOSE_ID, (long)0);
        
        // Logi
        //Log.i(LOG_TAG, "Zaczytano z pamieci, REGION_CHOOSE_ID: " + regionChooseId);
        
        // Ustalam pozycje wybranego wojewodztwa
        int regionChoose = Functions.getRegionPosision((int)regionChooseId, regionChooseCursor);
        
        // Upewniam sie, ze ustalona pozycja nie wykracza poza zakres danych
        if (regionChoose > regionChooseCursor.getCount() - 1) {
        	regionChoose = 0;
        }
        
        // Zaznaczam pozycje pod warunkiem, ze jest cokolewiek na liscie
        if (regionChooseCursor.getCount() > 0) {
        	regionChooseSpinner.setSelection(regionChoose);
        }
        
        // Logi
        //Log.i(LOG_TAG, "Zaczytano z pamieci, regionChoose: " + regionChoose);
        
        // Reagowanie na wybor wojewodztwa - automatyczne zapisanie ustawien
        regionChooseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
		        long currentRegionChooseId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.REGION_CHOOSE_ID, (long)0);
				if (currentRegionChooseId != id) {
					// Resetowanie powiatu
					PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.COUNTRY_CHOOSE_ID, (long)0);
					
					// Zapisanie regionu pozycji i identyfikatora
					PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.REGION_CHOOSE_ID, id);

			        // Logi
			        //Log.i(LOG_TAG, "Zmiana wojewodztwa, REGION_CHOOSE_ID: " + id);
			        
					// Tworze adapter, ktory pobierze dane dla obiektu countryChooseSpinner
			        String where = Countries.REGION_ID + "=" + id;
					Cursor countryChooseCursor = managedQuery(Countries.CONTENT_URI, REGION_AND_COUNTRY_PROJECTION, where, null, Countries.DEFAULT_SORT_ORDER);			
					SimpleCursorAdapter countryChooseAdapter = new SimpleCursorAdapter(ConfigActivity.this, android.R.layout.simple_spinner_item, countryChooseCursor, new String[] {Countries.NAME}, new int[] {android.R.id.text1});
					countryChooseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					
			        // Pobieram spinner "Wybierz powiat" i ustawiam jego wartosc na 0 poniewaz zostal zresetowany
			        Spinner countryChooseSpinner = (Spinner) findViewById(R.id.configCountryChooseSpinner);
			        countryChooseSpinner.setAdapter(countryChooseAdapter);
			        countryChooseSpinner.setSelection(0); // na pozycji " brak "

			        // Logi
			        //Log.i(LOG_TAG, "Zmiana powiatu, countryChoose: 0");
			        
					// Komunikat
					NotificationSupportManager.showToastNotification(ConfigActivity.this.getApplicationContext(), getString(R.string.notification_saved));
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
  
        // Tworze adapter, ktory pobierze dane dla obiektu spinner
		String where = Countries.REGION_ID + "=" + regionChooseId;
		Cursor countryChooseCursor = managedQuery(Countries.CONTENT_URI, REGION_AND_COUNTRY_PROJECTION, where, null, Countries.DEFAULT_SORT_ORDER);			
		SimpleCursorAdapter countryChooseAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, countryChooseCursor, new String[] {Countries.NAME}, new int[] {android.R.id.text1});
		countryChooseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        // Pobieram spinner "Wybierz powiat" i ustawiam jego wartosc
        Spinner countryChooseSpinner = (Spinner) findViewById(R.id.configCountryChooseSpinner);
        countryChooseSpinner.setAdapter(countryChooseAdapter);
        
        // Pobieram identyfikator zapamietanego powiatu
        long countryChooseId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.COUNTRY_CHOOSE_ID, (long)0);

        // Logi
        //Log.i(LOG_TAG, "Zaczytano z pamieci, COUNTRY_CHOOSE_ID: " + countryChooseId);
        
        // Ustalam pozycje wybranego powiatu
        int countryChoose = Functions.getCountryPosision((int)countryChooseId, countryChooseCursor);

        // Upewniam sie, ze ustalona pozycja nie wykracza poza zakres danych
        if (countryChoose > countryChooseCursor.getCount() - 1) {
        	countryChoose = 0;
        }

        // Zaznaczam pozycje pod warunkiem, ze jest cokolewiek na liscie
        if (countryChooseCursor.getCount() > 0) {
            countryChooseSpinner.setSelection(countryChoose);
        }

        // Logi
        //Log.i(LOG_TAG, "Zaczytano z pamieci, countryChoose: " + countryChoose);
        
        // Reagowanie na wybor powiatu - automatyczne zapisanie ustawien
        countryChooseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
		        long currentCountryChooseId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.COUNTRY_CHOOSE_ID, (long)0);
				if (currentCountryChooseId != id) {
					// Zapisanie country pozycji i identyfikatora
					PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.COUNTRY_CHOOSE_ID, id);

			        // Logi
			        //Log.i(LOG_TAG, "Zmiana powiatu, COUNTRY_CHOOSE_ID: " + id);
			        
					// Komunikat
					NotificationSupportManager.showToastNotification(ConfigActivity.this.getApplicationContext(), getString(R.string.notification_saved));
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
        
        // Pobieram przycisk "Lista sieci bankomatow"
        Button preferedOwnersButton = (Button) findViewById(R.id.configPreferedOwnersButton);
        preferedOwnersButton.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	ConfigActivity.this.owners();
	        }
        });
    }
    
    /**
     * Funkcja wspomagajaca zapisanie danych z formularza
     */
    protected void save() {
    	// Pobieram zawartosc pola i zapisuje ja do propertisow
        EditText serverAddressEditText = (EditText)findViewById(R.id.configServerAddressEditText);
        String serverAddress = serverAddressEditText.getText().toString();
        if (serverAddress == null) {
        	serverAddress = "";
        }
        PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.SERVER_ADDRESS, serverAddress);
     
        // Pobieram zawartosc pola i zapisuje ja do propertisow
        EditText googleKeyMapsEditText = (EditText)findViewById(R.id.configGoogleKeyMapsEditText);
        String googleKeyMaps = googleKeyMapsEditText.getText().toString();
        if (googleKeyMaps == null) {
        	googleKeyMaps = "";
        }
        PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.GOOGLE_KEY_MAPS, googleKeyMaps);
        
        // Pobieram zawartosc pola i zapisuje ja do propertisow
        CheckBox automaticUploadCheckBox = (CheckBox)findViewById(R.id.configAutomaticUploadCheckBox);
        boolean automaticUpload = automaticUploadCheckBox.isChecked();
        PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.IS_AUTOUPDATE_ON, automaticUpload);
        
        // Komunikat konczacy
		NotificationSupportManager.showToastNotification(getApplicationContext(), getString(R.string.notification_saved));
	}

	/**
     * Funkcja budowania menu.
     */
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_QUIT, 0, getString(R.string.menu_exit)).setIcon(R.drawable.menu_close);
        return true;
    }

    /**
     * Obsluga zdarzenia wybrania opcji z menu.
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case MENU_QUIT:
        		quit();
        		return true;
        }
	    
        return false;
    }

    /**
     * Funkcja konczenia aplikacji.
     */
    private void quit() {
    	this.finish();
    }

    /**
     * Funkcja konczenia aplikacji.
     */
    private void owners() {
		startActivity(new Intent(this, OwnersActivity.class));
    }
}